package com.ruoyi.app.common;

import com.alibaba.fastjson.JSON;
import lombok.extern.java.Log;
import lombok.val;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Log
public class Sign {
    static final String API_HTTP_METHOD = "POST";
    static final String VIDEO_API_VERSION = "2020-03-20";
    static final String PIC_API_VERSION = "2019-12-30";

    public static final String VIDEO_REQUEST_URL = "http://videoenhan.cn-shanghai.aliyuncs.com/?Signature=";
    public static final String PIC__REQUEST_URL = "http://facebody.cn-shanghai.aliyuncs.com/?Signature=";

    public static String accessKeyId = "LTAI5tRQ1acQfyPAnkCWvMAd";
    public static String accessSecret = "SVVk0Non9jDhpSdISorUnfYZFBqs9c";
    static final java.text.SimpleDateFormat DF = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");


    public static String addSegmentCommonImage(String url, String returnForm) throws Exception {
        DF.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));// 这里一定要设置GMT时区
        Map<String, String> params = new HashMap<>();//业务参数名字是大驼峰
        params.put("ImageURL", url);
        params.put("ReturnForm", returnForm);
        String action = "SegmentCommonImage";
        return Optional.ofNullable(execute(action, accessKeyId, accessSecret, params, 2))
                .map(JSON::parseObject)
                .map(jsonObject -> {
                    val data = jsonObject.getString("Data");
                    log.info("执行图片处理的处理结果是:" + data);
                    return JSON.parseObject(data).getString("ImageURL");
                }).orElse(null);
    }



    /**
     * 请求换脸
     * @return 返回requestId
     * @throws Exception 异常
     */
    public static String requestChangeFace(String videoUrl, String postUrl, String referenceUrl, Boolean addWatermark) throws Exception {
        DF.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));// 这里一定要设置GMT时区
        Map<String, String> params = new HashMap<>();//业务参数名字是大驼峰
        params.put("VideoURL", videoUrl);
        params.put("PostURL", postUrl);
        params.put("ReferenceURL", referenceUrl);
        params.put("AddWatermark", String.valueOf(addWatermark));
        params.put("Enhance", String.valueOf(true));
        params.put("WatermarkType", "CN");
        String action = "MergeVideoFace";
        return Optional.ofNullable(execute(action, accessKeyId, accessSecret, params, 1))
                .map(JSON::parseObject)
                .map(jsonObject -> jsonObject.getString("RequestId"))
                .orElse(null);
    }

    public static String addImageFaceTemplate(String url) throws Exception {
        DF.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));// 这里一定要设置GMT时区
        Map<String, String> params = new HashMap<>();//业务参数名字是大驼峰
        params.put("ImageURL", url);
        String action = "AddFaceImageTemplate";
        return Optional.ofNullable(execute(action, accessKeyId, accessSecret, params, 2))
                .map(JSON::parseObject)
                .map(jsonObject -> {
                    val data = jsonObject.getString("Data");
                    log.info("执行模板新增的处理结果是:" + data);
                    return JSON.parseObject(data).getString("TemplateId");
                }).orElse(null);
    }

    public static String removeImageFaceTemplate(String templateId) throws Exception {
        DF.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));// 这里一定要设置GMT时区
        Map<String, String> params = new HashMap<>();//业务参数名字是大驼峰
        params.put("TemplateId", templateId);
        String action = "DeleteFaceImageTemplate";
        return Optional.ofNullable(execute(action, accessKeyId, accessSecret, params, 2))
                .map(JSON::parseObject)
                .map(jsonObject -> {
                    val data = jsonObject.getString("RequestId");
                    log.info("执行模板移除的处理结果是:" + data);
                    return data;
                }).orElse(null);
    }

    /**
     * 请求换脸
     * @return 返回requestId
     * @throws Exception 异常
     */
    public static String requestChangeImageFace(String templateId, String imageUrl) throws Exception {
        DF.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));// 这里一定要设置GMT时区
        Map<String, String> params = new HashMap<>();//业务参数名字是大驼峰
        params.put("TemplateId", templateId);
        params.put("ImageURL", imageUrl);
        String action = "MergeImageFace";
        val execute = execute(action, accessKeyId, accessSecret, params, 2);
        System.out.println("执行结果是" + execute);
        return Optional.ofNullable(execute)
                .map(JSON::parseObject)
                .map(jsonObject1 -> {
                    val data = jsonObject1.getString("Data");
                    log.info("执行换脸处理的处理结果是:" + data);
                    return JSON.parseObject(data).getString("ImageURL");
                })
                .orElse(null);
    }

    public static String asyncTask(String jobId) throws Exception {
        DF.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));// 这里一定要设置GMT时区
        Map<String, String> params = new HashMap<>();//业务参数名字是大驼峰
        params.put("JobId", jobId);
        String action = "GetAsyncJobResult";
        return Optional.ofNullable(execute(action, accessKeyId, accessSecret, params, 1))
                .map(JSON::parseObject)
                .map(jsonObject -> {
                    val data = jsonObject.getString("Data");
                    log.info("data = " + data);
                    return data;
                })
                .orElse(null);
    }

    public static String execute(String action, String accessKeyId, String accessSecret, Map<String, String> bizParams, int type) throws Exception {
        java.util.Map<String, String> paras = new java.util.HashMap<String, String>();
        // 1. 系统参数
        paras.put("SignatureMethod", "HMAC-SHA1");
        paras.put("SignatureNonce", java.util.UUID.randomUUID().toString());//防止重放攻击
        paras.put("AccessKeyId", accessKeyId);
        paras.put("SignatureVersion", "1.0");
        paras.put("Timestamp", DF.format(new java.util.Date()));
        paras.put("Format", "JSON");
        // 2. 业务API参数
        paras.put("RegionId", "cn-shanghai");
        if (type == 1) {
            paras.put("Version", VIDEO_API_VERSION);
        }else {
            paras.put("Version", PIC_API_VERSION);
        }

        paras.put("Action", action);
        if (bizParams != null && !bizParams.isEmpty()) {
            paras.putAll(bizParams);
        }
        // 3. 去除签名关键字Key
        if (paras.containsKey("Signature")) {
            paras.remove("Signature");
        }
        // 4. 参数KEY排序
        java.util.TreeMap<String, String> sortParas = new java.util.TreeMap<String, String>();
        sortParas.putAll(paras);
        // 5. 构造待签名的字符串
        java.util.Iterator<String> it = sortParas.keySet().iterator();
        StringBuilder sortQueryStringTmp = new StringBuilder();
        StringBuilder sortQueryStringTmp1 = new StringBuilder();
        while (it.hasNext()) {
            String key = it.next();
            sortQueryStringTmp.append("&").append(specialUrlEncode(key)).append("=").append(specialUrlEncode(paras.get(key)));
            sortQueryStringTmp1.append("&").append(key).append("=").append(paras.get(key));
        }
        String sortedQueryString = sortQueryStringTmp.substring(1);// 去除第一个多余的&符号
        StringBuilder stringToSign = new StringBuilder();
        stringToSign.append(API_HTTP_METHOD).append("&");
        stringToSign.append(specialUrlEncode("/")).append("&");
        stringToSign.append(specialUrlEncode(sortedQueryString));
        String sign = sign(accessSecret + "&", stringToSign.toString());
        // 6. 签名最后也要做特殊URL编码
        String signature = specialUrlEncode(sign);

        // 添加直接做post请求的方法
        try {
            // 使用生成的 URL 创建POST请求
            URIBuilder builder;
            if (type == 1) {
                builder = new URIBuilder(VIDEO_REQUEST_URL + signature + sortQueryStringTmp);
            }else {
                builder = new URIBuilder(PIC__REQUEST_URL + signature + sortQueryStringTmp);
            }
            URI uri = builder.build();
            HttpPost request = new HttpPost(uri);
            HttpClient httpclient = HttpClients.createDefault();
            HttpResponse response = httpclient.execute(request);

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                return EntityUtils.toString(entity);
            }else {

                HttpEntity entity = response.getEntity();
                throw new Exception("解析失败" +  EntityUtils.toString(entity));
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }


    public static String specialUrlEncode(String value) throws Exception {
        return java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
    }
    public static String sign(String accessSecret, String stringToSign) throws Exception {
        javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
        mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return new sun.misc.BASE64Encoder().encode(signData);
    }
}
